package com.magtonic.wuii;

import com.magtonic.communication.BTSerial;

import android.bluetooth.*;
import android.content.*;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.*;
import android.util.Log;
import android.view.*;
import android.widget.Toast;

public class DeviceListActivity extends PreferenceActivity 
								implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
	final static boolean DEBUG = true;
	final static String TAG = "DeviceListActivity";
	//
	final static String OPEN_KEY = "open_bt";
	final static String PAIR_KEY = "pair_bt";
	final static String DISCOVER_KEY = "discover_bt";
	//
	BTSerial btSerial;
	
	final BroadcastReceiver btBrocastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent){
			onReceive_btBrocastReceiver(context, intent);
		}
	};
	
	IntentFilter btActionFoundFilter = new IntentFilter();
	//
	@Override
    public void onCreate(Bundle savedInstanceState) {
        //bluetooth 
        btSerial = new BTSerial();
        btActionFoundFilter.addAction(BluetoothDevice.ACTION_FOUND);
    	btActionFoundFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(btBrocastReceiver, btActionFoundFilter);
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //
        super.onCreate(savedInstanceState);
        //             
        this.setPreferenceScreen(createPreferenceHierarchy());
    }


    @Override
	protected void onDestroy() {
    	//bluetooth
    	btSerial.cancelDiscovery();
    	this.unregisterReceiver(btBrocastReceiver);
    	//
		super.onDestroy();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(DEBUG) Log.d(TAG, "onActivityResult " + requestCode + " " + resultCode);
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode == RESULT_CANCELED)  return;
		//
		switch(requestCode){
			case BTSerial.REQUEST_ENABLE_BT:
				if (resultCode == RESULT_OK) {
		            // Bluetooth is now enabled, so set up 
			        //btService = new BTService(this, bluetoothAdapter, mCallBackHandler);
					openPref.setChecked(true);
		        } else {
		            // User did not enable Bluetooth or an error occurred
		        	//if(DEBUG)  Log.d(TAG, "BT not enabled");
		        	openPref.setChecked(false);
		        	
		            Toast.makeText(this, "Bluetooth no enabled", Toast.LENGTH_LONG).show();
		            
		            finish();
		        }
				break;
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_device_list, menu);
        return true;
    }
    //
    SharedPreferences sharePrefs;
    PreferenceScreen root;
    PreferenceCategory launcherPrefCat;
    CheckBoxPreference openPref;
    ListPreference pairedPref;
    Preference discoverPref;
    PreferenceCategory devicePrefCat;
    
    //Preference devicePref[];
    
    String devSelected;
    int nSelected;
    
    private PreferenceScreen createPreferenceHierarchy() {
    	Resources res = this.getResources();
    	sharePrefs = PreferenceManager.getDefaultSharedPreferences(this);  
        // Root
        root = getPreferenceManager().createPreferenceScreen(this);
        // Root--launcher
        launcherPrefCat = new PreferenceCategory(this);
        launcherPrefCat.setTitle(R.string.string_launch);
        root.addPreference(launcherPrefCat);
        // Root-launcher--open
        openPref = new CheckBoxPreference(this);
        openPref.setKey(OPEN_KEY);    
        openPref.setTitle(res.getStringArray(R.array.string_bluetooth_launcher_arr)[0]);
        openPref.setSummary(res.getStringArray(R.array.string_bluetooth_launcher_summary_arr)[0]);
        openPref.setOnPreferenceClickListener(this);
        launcherPrefCat.addPreference(openPref);
        if(btSerial.getEnableStatus()){
        	openPref.setChecked(true);
        }
        else{
        	openPref.setChecked(false);
        }
        // Root-launcher-pair
        pairedPref = new ListPreference(this); 
        pairedPref.setKey(PAIR_KEY);
        pairedPref.setTitle(res.getStringArray(R.array.string_bluetooth_launcher_arr)[1]);
        pairedPref.setSummary(res.getStringArray(R.array.string_bluetooth_launcher_summary_arr)[1]);
        pairedPref.setDialogTitle(R.string.string_paired);
        pairedPref.setEntries(R.array.string_bluetooth_launcher_arr);
        pairedPref.setEntryValues(R.array.string_bluetooth_launcher_summary_arr);  
        pairedPref.setOnPreferenceChangeListener(this);
        launcherPrefCat.addPreference(pairedPref);
        // Root-launcher-discover
        discoverPref = new Preference(this);
        discoverPref.setKey(DISCOVER_KEY);
        discoverPref.setTitle(res.getStringArray(R.array.string_bluetooth_launcher_arr)[2]);
        discoverPref.setSummary(res.getStringArray(R.array.string_bluetooth_launcher_summary_arr)[2]);
        discoverPref.setOnPreferenceClickListener(this);
        launcherPrefCat.addPreference(discoverPref);
        // Root-Device
        devicePrefCat = new PreferenceCategory(this);
        devicePrefCat.setTitle(R.string.string_device);
        root.addPreference(devicePrefCat);
        
        devSelected = "";
        nSelected = 0;
        
        return root;
    }
    
	public boolean onPreferenceClick(Preference preference) {
		if(DEBUG) Log.d(TAG, "onPreferenceClick " + preference.getKey());
		//
		if(preference.getKey().equals(OPEN_KEY)){
			if(sharePrefs.getBoolean(OPEN_KEY, false)){
				openPref.setSummary("open");
				
				btSerial.setEnable(this);
			}
			else{
				openPref.setSummary("close");
				
				btSerial.setDisable();
			}
			return true;
		}
		else if(preference.getKey().equals(PAIR_KEY)){

		}
		else if(preference.getKey().equals(DISCOVER_KEY)){
			
			
			btSerial.startDiscovery();
			return true;
		}
		else{
			devSelected = preference.getKey();
			nSelected = preference.getOrder();
			//
			goBack();
		}
		return false;
	}

	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if(DEBUG) Log.d(TAG, "onPreferenceChange " + preference.getKey() + newValue.toString());
		
		if(preference.getKey().equals(PAIR_KEY)){
			sharePrefs.edit().putString(PAIR_KEY, newValue.toString()).commit();
			pairedPref.setSummary(sharePrefs.getString(PAIR_KEY, "nothing"));
			
			return true;
		}
		
		return false;
	}
	
	void goBack(){
		Intent resultIntent = new Intent(WUiiService.ACTION_WUII_BT_CONNECT);

		if(!devSelected.equals("")){
			resultIntent.putExtra(BTSerial.DEVICE_NAME, btSerial.mBluetoothList.get(nSelected).get(BTSerial.DEVICE_NAME));
			resultIntent.putExtra(BTSerial.DEVICE_ADDR, btSerial.mBluetoothList.get(nSelected).get(BTSerial.DEVICE_ADDR));
			
			//setResult(RESULT_OK, resultIntent);
			sendBroadcast(resultIntent);
		}
		else{
			resultIntent.putExtra(BTSerial.DEVICE_NAME, 0);
			resultIntent.putExtra(BTSerial.DEVICE_ADDR, 0);
			
			//setResult(RESULT_CANCELED, resultIntent);
			sendBroadcast(resultIntent);
		}
		
		finish();
	}
	
	@Override
	public void onBackPressed() {
		if(DEBUG) Log.d(TAG, "onBackPressed ");
		//
		super.onBackPressed();		
		//goBack();
	}
	
    private void addDeviceItems(){ 	
    	devicePrefCat.removeAll();
	
    	for(int i=0; i<btSerial.btdCnt; i++){
	    	Preference devicePref = new Preference(this);
	    	devicePref.setOrder(i);
	    	devicePref.setKey(btSerial.mBluetoothList.get(i).get(BTSerial.DEVICE_NAME));
			devicePref.setTitle(btSerial.mBluetoothList.get(i).get(BTSerial.DEVICE_NAME));
			devicePref.setSummary(btSerial.mBluetoothList.get(i).get(BTSerial.DEVICE_ADDR));
			devicePref.setOnPreferenceClickListener(this);
			devicePrefCat.addPreference(devicePref);
    	}
    }
	//
	private void onReceive_btBrocastReceiver(Context context,	Intent intent) {
		if(DEBUG) Log.d(TAG, "onReceive_btBrocastReceiver " + intent.getAction());
		//
		if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
			btSerial.onReceive(context, intent);

			if(btSerial.btdCnt > 0){
				addDeviceItems();
			}
		}
		else if(intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
			if(btSerial.btdCnt > 0){
				Toast.makeText(context, "Total Device " + btSerial.btdCnt + " Found !!!", Toast.LENGTH_SHORT).show();
			}
			else{
				Toast.makeText(context, "No Device Found !!!", Toast.LENGTH_SHORT).show();
			}
		}
	}
}
